<template>
  <div class="chat-container">
	 
    <div class="chat-content" ref="chatContent">
		
      <div v-for="(message, index) in messages" :key="index" class="message-item">
		 
        <div v-if="message. senderUserid === myinfo.userid" class="user-message">
          <div class="avatar left">
            <img :src="downURL+myphoto" class="avatar-image" />
          </div>
          <div class="message-content">{{ message.content }}</div>
        </div>
        <div v-else class="merchant-message">
			<div class="message-content-box">
				 <div class="message-content">{{ message.content }}</div>
			 
			</div>
          <div class="avatar right">
            <img :src="downURL+sellerphoto" class="avatar-image" />
          </div>
        </div>
      </div>
    </div>
    <div class="input-box">
      <div class="input-row">
        <textarea v-model="inputMessage"  @input="handleInput" :style="{ height: inputMessage.split('\n').length * 1.5 + 'em' }" />
        <button @click="sendMessage">发送</button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
		sellerid:'',
		sellerphoto:'',
		myinfo:null,
		token:'',
		friendName:'',
		myphoto:'',
		homestayId:'',
		downURL:"http://localhost:8086/business/common2/download?name=",
		myuserid:'',
		
      messages: [
        
      ],
      userAvatar: 'https://tupian.qqw21.com/article/UploadPic/2020-10/2020101722211881489.jpg',
      merchantAvatar: 'https://tupian.qqw21.com/article/UploadPic/2021-1/202111921572761327.jpg',
      inputMessage: '',
      maxCharsPerLine: 20, // 每行最大字符数
      ws: "ws:",
	  socket:null,
	  sendmessage:{
		  chatId:'',
		  senderUserid:this.myuserid,
		  receiverUserid:this.sellerid,
		  senderType:0,
		  receiverType:1,
		  content:'',
		  sendTime:'',
		  homestayId:this.homestayId,
		  isread:0
	  }
    };
  },
  
  // onLoad(query) {
	  mounted(){
	  
      // 通过this.$route.query获取参数
	  this.sellerid = this.$route.query.friendId,
	  
	  this.friendName = this.$route.query.friendName,
	  this.homestayId = this.$route.query.homestayId,
	  this.sellerphoto  =this.$route.query.photo,
	  this.myuserid = uni.getStorageSync('login-user').userId,
	  // 设置导航栏标题
	      uni.setNavigationBarTitle({
	        title:this.friendName
	      });
	  //获取个人信息
	  this.get_user_info();
		// this.connectWebSocket();
		
		//查询聊天记录
	 this.getChatRecords();
	 
	 //建立连接
	 this.socket = new WebSocket('ws://localhost:8086/chat?userid='+this.myuserid+'0');
	
      
	 
    },
	// 在需要返回并刷新的页面的逻辑代码中
	onUnload() {
	  uni.navigateBack({
	    delta: 1, // 返回上一个页面
	    success: function() {
	      uni.$emit('refreshFriendList'); // 触发事件，通知上一个页面刷新好友列表数据
	    }
	  });
	},
  methods: {
    handleInput(event) {
      this.inputMessage = event.target.value;
    },
    sendMessage() {
      if (this.inputMessage.trim() === '') {
        return;
      }
	  this.sendmessage.content = this.inputMessage;
	  this.sendmessage.senderUserid = this.myuserid;
	  this.sendmessage.receiverUserid=this.sellerid;
	  this.sendmessage.homestayId = this.homestayId;
	  
      
      // 发送消息到 WebSocket 服务器
	 
      this.socket.send( JSON.stringify(this.sendmessage));
	  this.messages.push(this.sendmessage);
	  //恢复输入框
      this.inputMessage = '';
      this.$nextTick(() => {
        this.$refs.chatContent.scrollTop = this.$refs.chatContent.scrollHeight;
      });
    },
    // 获取聊天记录
	getChatRecords(){
		uni.request({
			url:"http://localhost:8086/business/user/chatContent/chatRecords",
			method:'GET',
			data: {
			    // myuserid: this.myinfo.userid,
				myuserid: this.myuserid,
			    friendid: this.sellerid,
			    homestayId: this.homestayId
			  },
			  // header:{
				 //  'token': this.token 
			  // },
			  success:(res)=>{
				  console.log("聊天记录为")
				  console.log(res.data.data)
				  this.messages =res.data.data
			  },
			  fail:(err)=>{
				  console.log("请求出错")
			  }
			
		})
	},
	
	//获取个人信息
	get_user_info(){
		this.token=uni.getStorageSync('login-user').token;
		console.log(this.token);
		uni.request({
		 	url:"http://localhost:8086/business/user/getinfo",
		 	method:'GET',
			header: {
			        'token': this.token // 在这里设置请求头
			    },
			
		 	// 返回成功的结果
		 	success:(res) =>{
				console.log(res.data.data);
				this.myinfo = res.data.data;
				console.log("个人信息为")
				console.log(this.myinfo.photo);
				this.myphoto = this.myinfo.photo
				// Element.success(this.myinfo.password)
			
			},
		 	fail:(error) => {
		 		Element.error("个人信息获取失败!")
		 	},
		 })
		
	},
	
	
	
  },
};
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.chat-content {
  flex: 1;
  padding: 10px;
  overflow-y: auto; /* 调整为滚动显示 */
}

.message-item {
  display: flex;
  margin-bottom: 10px;
  align-items: flex-start;
}

.avatar {
  width: 40px;
  height: 40px;
}

.avatar-image {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

.message-content {
  padding: 10px;
  border-radius: 10px;
 
  word-break: break-all;
   background-color:whitesmoke;
   margin-left: 10px;
   display: inline-block; /* 设置为内联块元素 */
   max-width: 17rem; /* 设置最大宽度，超出部分会自动换行 */
   word-wrap: break-word; /* 当单词或 URL 超出容器时自动换行 */
  
}

.user-message {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin-bottom: 10px;
 
  
}

.merchant-message {
  display: flex;
  align-items: flex-start;
  justify-content: flex-end; /* 调整消息内容和右侧头像的对齐方式 */
  margin-bottom: 10px;
 
}
.merchant-message .message-content-box{
	 min-width: 22rem; 
	 /* min-width: 100%; */
	
	/* background-color: bisque; */
	text-align: right;
	
}

.merchant-message .avatar.right {
  margin-left: auto; /* 将右侧头像推到屏幕最右侧 */
  margin-right: 10px; /* 调整右侧头像与内容的距离 */
   
}

.merchant-message .message-content {
  margin-left: auto; /* 将右侧头像推到屏幕最右侧 */
  
  margin-right: 10px; /* 调整内容与右侧头像的距离 */
  background-color: aquamarine;
  text-align: left;
  min-width: 0vmin; /* 设置最小宽度为内容的宽度 */
  display: inline-block; /* 设置为内联块元素 */
  max-width: 17rem; /* 设置最大宽度，超出部分会自动换行 */
  word-wrap: break-word; /* 当单词或 URL 超出容器时自动换行 */
  
 
}


.input-box {
  display: flex;
  flex-direction: column; /* 修改为垂直布局 */
  padding: 10px;
  position: fixed;
  bottom: 0;
  width: 100%;
  background-color: #fff;
  
}

.input-row {
  display: flex;
  align-items: center; /* 垂直居中 */
}
textarea {
  flex: 1; /* 输入框占据剩余空间 */
  padding: 10px;
  margin-bottom: 0px; /* 调整输入框与发送按钮的间距 */
  border-radius: 5px;
  border: 1px solid #ccc;
  resize: none; /* 禁止文本框大小调整 */
  height: auto; /* 设置高度为自适应 */
  min-height: 30px; /* 设置最小高度 */
  line-height: 1.5; /* 设置行高为 1.5倍字体大小 */
  word-wrap: break-word; /* 当单词或 URL 超出容器时自动换行 */
  margin-top: 0px;
  

  
 
}

button {
  /* padding: 10px 20px; */
  border-radius: 5px;
  background-color: limegreen;
  color: #fff;
  border: none;
  text-align: center;
  margin-top: 0px;
  max-width: max-content;
  max-height: max-content;
  min-height: 30px;
   
  
}
</style>